package com.yj.spring.charpter02;

import cn.hutool.core.collection.CollUtil;
import com.yj.spring.common.ArgumentValue;
import com.yj.spring.common.BeanDefinition;
import com.yj.spring.common.PropertyValue;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class SimpleBeanFactory implements BeanFactory {

    private List<String> beanNames = new ArrayList<>();
    private Map<String, Object> singletonObjects = new HashMap<>();

    private List<BeanDefinition> beanDefinitions = new ArrayList<>();

    public SimpleBeanFactory() {
    }

    @Override
    public Object getBean(String beanId) {
        Object bean = singletonObjects.get(beanId);
        if (bean == null) {
            int i = beanNames.indexOf(beanId);
            if (i == -1) {
                throw new IllegalArgumentException("No such bean named " + beanId);
            } else {
                bean = doCreateBean(beanId);
                singletonObjects.put(beanId, bean);
            }
        }
        return bean;
    }

    private Object doCreateBean(String beanId) {
        Object bean = null;
        int i = beanNames.indexOf(beanId);
        BeanDefinition beanDefinition = beanDefinitions.get(i);
        String className = beanDefinition.getClassName();
        try {
            Class clazz = Class.forName(className);

            List<PropertyValue> propertyValues = beanDefinition.getPropertyValues();
            if (CollUtil.isNotEmpty(propertyValues)) {
                bean = clazz.newInstance();
                for (PropertyValue propertyValue : propertyValues) {
                    String name = propertyValue.getName();
                    Object value = propertyValue.getValue();
                    try {
                        Field field = bean.getClass().getDeclaredField(name);
                        field.setAccessible(true);
                        field.set(bean, value);
                    } catch (Exception e) {
                        throw new RuntimeException("No such field named: " + name + " in class: " + clazz.getName());
                    }
                }
            }
            if (CollUtil.isNotEmpty(beanDefinition.getArgumentValues())) {
                List<ArgumentValue> argumentValues = beanDefinition.getArgumentValues();
                List<Class> list = argumentValues.stream().map(x -> {
                    try {
                        return Class.forName(x.getType());
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                }).collect(Collectors.toList());
                Constructor declaredConstructor = clazz.getDeclaredConstructor(list.toArray(new Class[0]));
                declaredConstructor.setAccessible(true);
                List<Object> args = argumentValues.stream().map(x -> x.getValue()).collect(Collectors.toList());
                bean = declaredConstructor.newInstance(args.toArray());
            }
            return bean;
        } catch (Exception e) {
            throw new RuntimeException("Create bean failed: " + e.getMessage());
        }
    }

    @Override
    public void registerBeanDefinition(BeanDefinition beanDefinition) {
        beanNames.add(beanDefinition.getId());
        beanDefinitions.add(beanDefinition);
    }

    @Override
    public void removeBean(String beanId) {
        singletonObjects.remove(beanId);
    }
}
